package com.jnu.myfirstapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jnu.myfirstapplication.data.Book;
import com.jnu.myfirstapplication.data.DataSaver;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookItemFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookItemFragment extends Fragment {

    private static final int MENU_ID_ADD=1;
    private static final int MENU_ID_UPDATE=2;
    private static final int MENU_ID_DELETE=3;
    private BookItemFragment.BookRecycleViewAdapter bookRecycleViewAdapter;
    private ArrayList<Book> bookList = new ArrayList<>();

    private ActivityResultLauncher<Intent> addDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (null != result) {
                    Intent intent=result.getData();
                    if(result.getResultCode()==InputBookItemActivity.RESULT_CODE_SUCCESS){
                        Bundle bundle=intent.getExtras();
                        String title=bundle.getString("title");
                        Double price=bundle.getDouble("price");
                        int position=bundle.getInt("position");
                        bookList.add(position, new Book(title, R.drawable.ic_launcher_background,price));
                        bookRecycleViewAdapter.notifyItemInserted(position);
                        new DataSaver().save(this.getContext(),bookList);
                        //Toast.makeText(this, "input activity return", Toast.LENGTH_LONG).show();
                    }
                }
            });

    private ActivityResultLauncher<Intent> updateDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (null != result) {
                    Intent intent=result.getData();
                    if(result.getResultCode()==InputBookItemActivity.RESULT_CODE_SUCCESS){
                        Bundle bundle=intent.getExtras();
                        String title=bundle.getString("title");
                        Double price=bundle.getDouble("price");
                        int position=bundle.getInt("position");
                        bookList.get(position).setTitle(title);
                        bookList.get(position).setPrice(price);

                        bookRecycleViewAdapter.notifyItemChanged(position);
                        new DataSaver().save(this.getContext(),bookList);
                        //Toast.makeText(this, "input activity return", Toast.LENGTH_LONG).show();
                    }
                }
            });

    public BookItemFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment BookItemFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BookItemFragment newInstance() {
        BookItemFragment fragment = new BookItemFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initbookList();
        if (getArguments() != null) {

        }
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case MENU_ID_ADD:
                Intent intent = new Intent(this.getContext(), InputBookItemActivity.class);
                intent.putExtra("position",item.getOrder());
                addDataLauncher.launch(intent);
                break;
            case MENU_ID_UPDATE:
                Intent intentUpdate = new Intent(this.getContext(), InputBookItemActivity.class);
                intentUpdate.putExtra("position",item.getOrder());
                intentUpdate.putExtra("title",bookList.get(item.getOrder()).getTitle());
                intentUpdate.putExtra("price",bookList.get(item.getOrder()).getPrice());
                updateDataLauncher.launch(intentUpdate);
                break;
            case MENU_ID_DELETE:
                AlertDialog alertDialog = new AlertDialog.Builder(this.getContext())
                        .setTitle(R.string.string_confirmation)
                        .setMessage(R.string.string_sure_to_delete)
                        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                bookList.remove(item.getOrder());
                                new DataSaver().save( BookItemFragment.this.getContext(),bookList);
                                bookRecycleViewAdapter.notifyItemRemoved(item.getOrder());

                            }
                        }).create();

                alertDialog.show();
                break;
        }
        return super.onContextItemSelected(item);
    }

    private void initbookList() {
//        bookList.add(new Book("软件项目管理案例教程(第4版)", R.drawable.book_2,100));
//        bookList.add(new Book("创新工程实践", R.drawable.book_no_name,200));
//        bookList.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1,300));
    }


    public class BookRecycleViewAdapter extends RecyclerView.Adapter<BookRecycleViewAdapter.ViewHolder> {
        private List<Book> bookList;

        public BookRecycleViewAdapter(List<Book> bookList) {
            this.bookList = bookList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.book, viewGroup, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            Book book = bookList.get(position);
            viewHolder.getId().setImageResource(book.getCoverResourceId());
            viewHolder.getName().setText(book.getTitle());
            viewHolder.getPrice().setText(""+book.getPrice());
        }

        @Override
        public int getItemCount() {
            return bookList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            TextView name;
            TextView price;

            public TextView getPrice() {
                return price;
            }


            ImageView id;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                id = itemView.findViewById(R.id.image_view_book_cover);
                name = itemView.findViewById(R.id.text_view_book_title);
                price=itemView.findViewById(R.id.text_view_book_price);

                itemView.setOnCreateContextMenuListener(this);
            }

            public TextView getName() {
                return name;
            }

            public ImageView getId() {
                return id;
            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                contextMenu.add(0, MENU_ID_ADD, getAdapterPosition(), "Add" + getAdapterPosition());
                contextMenu.add(0, MENU_ID_UPDATE, getAdapterPosition(), "Update" + getAdapterPosition());
                contextMenu.add(0, MENU_ID_DELETE, getAdapterPosition(), "Delete" + getAdapterPosition());

            }
        }

//        public boolean onKeyDown(int keyCode, KeyEvent event){
//            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
//            {
//                //操作
//            }
//        }
//        @Override
//        public void onBackPressed() {
//                //操作
//            return;
//        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_book_item,container,false);
        RecyclerView recycle_view_books = rootView.findViewById(R.id.recycleview_main2);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getContext());
        recycle_view_books.setLayoutManager(linearLayoutManager);
//        ImageButton imageButton=rootView.findViewById(R.id.fab_menu_add);
//        imageButton.setImageResource(R.drawable.ic_add);

        bookList=new DataSaver().Load(this.getContext());
        if(bookList.size()==0){
            bookList.add(new Book("软件项目管理案例教程(第4版)", R.drawable.book_2,100));
        }
        bookRecycleViewAdapter = new BookRecycleViewAdapter(bookList);
        recycle_view_books.setAdapter(bookRecycleViewAdapter);
        return rootView;
    }
}